import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import TreeMap
from pyecharts.globals import ThemeType
df=pd.read_excel('某店铺促销方式分析.xlsx')
total=df['购买人数'].sum()
tree=[]
for i in range(len(df.index)):
    dic={}
    dic['name']=df['促销方式'][i]
    dic['value']=round(int(df['购买人数'][i]/total*100,2))
    dic['children']=[
        {
            #讲当前促销方式和性别组合并赋给子节点的name关键字
            'name':df['促销方式'][i]+'-男',
            'value':round(int(df['男'][i])/total*100,2)},
        {
            #将当前促销方式和性别组合并赋给子节点的name关键字
            'name':df['促销方式'][i]+'-女',
            #计算机当前促销方式下的女性购买人数占比，并赋给子节点的value关键字
            'value':round(int(df['女'][i])/total*100,2)}]
    tree.append(dic)
    treemap=TreeMap(init_opts=opts.InitOpts(
        width='1000px',height='600px',
        theme=ThemeType.SHINE,page_title='矩形树图'))
    treemap.add(series_name='',data=tree,label_opts=opts.LabelOpts(formatter='{b}\n\n{c}%'),
                upper_label_opts=opts.LabelOpts(is_show=False),
                levels=[
                    opts.TreeMapLevelsOPts(
                        treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                            gap_width=2)),
                    opts.TreeMapLevelsOpts(
                    treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                        gap_width=1))])
    treemap.set_global_opts(
        title_opts=opts.TItleOpts(
            title='某店铺不同促销方式下男性和女性购买人数占比矩形树图',
            pos_left='center'),
        legend_opts=opts.LegendOpts(is_show=False))
    treemap.render('例6-3.html')



